var AssetModule = function() {
    var editable = function() {

        return {
            init: function() {
            	//格式化金额
            	function fmoney(s, n) {  
            	   if(s == ""|| undefined == s){
            		   return "--";
            	   }
                   n = n > 0 && n <= 20 ? n : 2;  
                   s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";//更改这里n数也可确定要保留的小数位  
                   var l = s.split(".")[0].split("").reverse(),  
                   r = s.split(".")[1];  
                   t = "";  
                   for(i = 0; i < l.length; i++ )  
                   {  
                      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
                   }
                   var str = t.split("").reverse().join("") + "." + r.substring(0,2);
                   return str;//保留2位小数  如果要改动 把substring 最后一位数改动就可  
                }
            	
                //表格初始化
                var oTable = $('#assetAllocationEditable').dataTable({
                	"bDestroy":true, 
                    "lengthMenu": [
                        [10, 15, 20, 50],
                        [10, 15, 20, 50]
                    ],
                    "autoWidth": true,
                    "scrollX": true,
                    "displayLength": 10,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "zeroRecords": "数据为空",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info": "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",
                        "infoEmpty": "记录数为0",
                    },
                    "columnDefs": [{
                        "data": null,
                        'sortable': false,
                        "defaultContent": "<center>---<center>",
                        "targets": [6]
                    }],
                    "columns": [{
                        "data": "name",
                        'sortable': false,
                        "defaultContent": ""
                    }, {
                        "data": "productName",
                        'sortable': false,
                        "defaultContent": ""
                    }, {
                        "data": "amount",
                        'sortable': false,
                        "defaultContent": ""
                    }, {
                        "data": "employeeName",
                        'sortable': false,
                        "defaultContent": ""
                    }, {
                        "data": "time",
                        'sortable': false,
                        "defaultContent": "<center>---<center>"
                    }, {
                        "data": "state",
                        'sortable': false,
                        "defaultContent": "<center>---<center>"
                    }, ],
                    "filter": false,
                    "processing": false,
                    "serverSide": true,
                    "ajaxSource": ctx + "/assetAllocation/queryAsset",
                    "serverMethod": "post",
                    "fnRowCallback": function(nRow, aData, displayIndex) {
                        nRow.children[0].id = aData.id;
                        var state = "";
                        var operation = ""
                    	switch(aData.state){
 	                	   case (2):
 	                		   state = "审批中";
 	                           break;
 	                       case (3):
 	                    	   state = "终审中";
                            	   break;
 	                       case (4):
 	                    	   state = "过终审";
                            	   break;
 	                       case (5):
 	                    	   state = "已投资";
                            	   break;
 	                       default:
 	                    	   state = "审批中";
                 	   }
                        operation =
                            '<a title="详情" class="detail fa fa-bars fa-lg pull" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;';
                        if(aData.operter!= null){
                        	operation = operation + aData.operter;
                 	   }
                        $('td:eq(5)', nRow).html(state);
                        $('td:eq(2)', nRow).html(fmoney(aData.amount));
                        $('td:eq(6)', nRow).html(operation);
                        return nRow;
                    },
                    "fnServerData": function(ajaxSource, dataSet, fnCallback) {
                        var json = "";
                        var s;
                        for (var i = 0; i < dataSet.length; i++) {
                            s = dataSet[i];
                            if (s.name == 'sEcho') {
                                json = json + '"echo":' + s.value;
                            } else if (s.name == 'iDisplayStart') {
                                json = json + ',"start":' + s.value;
                            } else if (s.name == 'iDisplayLength') {
                                json = json + ',"pageSize":' + s.value;
                            }
                        }
                        var orgId = $("#org_id").attr("value");
                        var form = $("form#queryForm").serializeJSON();
                        var js = form.replace('}', ',');
                        json = js + json + ',"orgId":"' + orgId + '"}';
                        $.ajax({
                            "contentType": "application/json; charset=UTF-8",
                            "dataType": 'json',
                            "type": "POST",
                            "url": ajaxSource,
                            "data": json,
                            "success": fnCallback
                        });
                    },
                });
                jQuery.validator.addMethod("mobileLength", function(value, element) {
                	var flag = !checkMobile(value.trim());
                	return flag;
                }, "联系电话输入有误.");
                
                //个人表决
                $('#assetAllocationEditable').on("click", "a.vote", function(e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    $('#eventId').attr('value',id);
                    var modal = $('#voteModal').modal('show');
                    var voteForm = $('#voteForm');
                    modal.on("hidden.bs.modal", function(e) {
                        $(this).removeData();
                        $("#voteForm")[0].reset();
                    });
                    
                    voteForm.validate({
                        focusInvalid: true,
                        rules: {
                        	result: {
                                required: true,
                            },
                            suggestion: {
                                required: true,
                            },
                        },
                        messages: {
                        	suggestion: {
                                required: "原因不能为空！",
                            },
                        },
                        success: function(label, element) {
                            var icon = $(element).parent('.input-icon').children('i');
                            $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                            icon.removeClass("fa-warning").addClass("fa-check");
                        },
                        submitHandler: function(form) {
                            var form = $("form#voteForm").serializeJSON();
                            var eventId = $('#eventId').val();
                            if (eventId == '') {
                            	bootbox.alert("请先选择资产配资");
                            	return;
                            }
                            var js = form.replace('}', ',');
                            var json = js + '"eventId" : "' + eventId + '"}'; 
                            $('#voteConfirm').attr('disabled', true);
                            $.ajax({
                                type: "post",
                                contentType: "application/json; charset=UTF-8",
                                url: ctx + "/assetAllocation/vote",
                                data: json,
                                dataType: "json",
                                success: function(msg) {
                                    if (msg.code == 1) {
                                        bootbox.alert("个人表决成功！");
                                        modal.modal('hide');
                                        oTable.fnDraw(false);
                    					window.location.reload();
                                    } else {
                                    	modal.modal('hide');
                                        bootbox.alert(msg.message);
                                    }
                                    $('#voteConfirm').attr('disabled', false);
                                },
                                error: function(msg) {
                                    bootbox.alert(msg.message);
                                    modal.modal('hide');
                                    $('#voteConfirm').attr('disabled', false);
                                }
                            });
                        }
                    });

                    $('#voteConfirm').unbind("click").click(function() {
                        timeout(this, 1);
                        voteForm.submit();
                        $("#voteForm")[0].reset();
                    });
                });
                
                //决策委员会负责人审批
                $('#assetAllocationEditable').on("click", "a.approve", function(e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    $('#eventIdApprove').attr('value',id);
                    var modal = $('#approveModal').modal('show');
                    var approveForm = $('#approveForm');
                    modal.on("hidden.bs.modal", function(e) {
                        $(this).removeData();
                        $("#approveForm")[0].reset();
                    });
                    //表格初始化
                    var oTable = $('#approveEditable').dataTable({
                    	"bDestroy":true, 
        	            "autoWidth":false,
        	            "paginate": false, //翻页功能
        	            "lengthChange": false, //改变每页显示数据数量
        	            "info": false,//页脚信息
        	            "language": {
                            "zeroRecords": "数据为空",
                        },
        	            "columnDefs": [
               						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [0]
            						},
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [1]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [2]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [3]
            						},
                                ],
        	            "columns": [{ "data": "employeeName" },
                                    { "data": "createTime" },
                                    { "data": "result" },
                                    { "data": "suggestion"},
                                    ],
        	           "filter" : false,
        	           "processing": false,
        	           "serverSide": true,
        	           "ajaxSource": ctx + "/assetAllocation/queryApprove/" + id,
        	           "serverMethod": "post",
        	           "fnRowCallback" : function(nRow, aData, displayIndex) {
        	        	   nRow.children[0].id = aData.id;
        	        	   
        	        	   var result = "";
                       	   switch(aData.result){//1同意，2不同意，3弃权
    	                	   case (1):
    	                		   result = "同意";
    	                           break;
    	                       case (2):
    	                    	   result = "不同意";
                               	   break;
    	                       case (3):
    	                    	   result = "弃权";
                               	   break;
    	                       default:
    	                    	   result = "未知结果";
                    	   }
                           $('td:eq(2)', nRow).html(result);
                    	   return nRow;
        	           },
        	           "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
                           $.ajax({
                           	"contentType":"application/json; charset=UTF-8",
                               "dataType" : 'json',
                               "type" : "POST",
                               "url" : ajaxSource,
                               "data" : "",
                               "success" : fnCallback
                           });
        	           },
                    });
                    
                    approveForm.validate({
                    	focusInvalid: true,
                    	rules: {
                    		approveResult: {
                    			required: true,
                    		},
                    		approveSuggestion: {
                    			required: true,
                    		},
                    	},
                    	messages: {
                    		approveSuggestion: {
                    			required: "原因不能为空！",
                    		},
                    	},
                    	success: function(label, element) {
                    		var icon = $(element).parent('.input-icon').children('i');
                    		$(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                    		icon.removeClass("fa-warning").addClass("fa-check");
                    	},
                    	submitHandler: function(approveForm) {
                    		var approveForm = $("form#approveForm").serializeJSON();
                    		var eventId = $('#eventIdApprove').val();
                    		if (eventId == '') {
                    			bootbox.alert("请先选择资产配资");
                    			return;
                    		}
                    		var js = approveForm.replace('approveResult', 'result').replace('approveSuggestion', 'suggestion').replace('}', ',');
                    		var json = js + '"eventId" : "' + eventId + '"}';
                    		$('#approveConfirm').attr('disabled', true);
                    		$.ajax({
                    			type: "post",
                    			contentType: "application/json; charset=UTF-8",
                    			url: ctx + "/assetAllocation/approve",
                    			data: json,
                    			dataType: "json",
                    			success: function(msg) {
                    				if (msg.code == 1) {
                    					bootbox.alert("审批成功！");
                    					modal.modal('hide');
                    					oTable.fnDraw(false);
                    					window.location.reload();
                    				} else {
                    					modal.modal('hide');
                    					bootbox.alert(msg.message);
                    				}
                    				$('#approveConfirm').attr('disabled', false);
                    			},
                    			error: function(msg) {
                    				bootbox.alert(msg.message);
                    				modal.modal('hide');
                    				$('#approveConfirm').attr('disabled', false);
                    			}
                    		});
                    	}
                    });
                    
                    //确认按钮，添加  决策委员会终审意见
                    $('#approveConfirm').unbind("click").click(function() {
                        timeout(this, 1);
                        approveForm.submit();
                        $("#approveForm")[0].reset();
                        
                    });
                    
                    
                });
                
                //终审人审批 
                $('#assetAllocationEditable').on("click", "a.approveFinal", function(e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    $('#eventIdApproveFinal').attr('value',id);
                    var modal = $('#approveFinalModal').modal('show');
                    var approveFinalForm = $('#approveFinalForm');
                    modal.on("hidden.bs.modal", function(e) {
                        $(this).removeData();
                        $("#approveFinalForm")[0].reset();
                    });
                    
                    approveFinalForm.validate({
                        focusInvalid: true,
                        rules: {
                        	result: {
                                required: true,
                            },
                            suggestion: {
                                required: true,
                            },
                        },
                        messages: {
                        	suggestion: {
                                required: "原因不能为空！",
                            },
                        },
                        success: function(label, element) {
                            var icon = $(element).parent('.input-icon').children('i');
                            $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                            icon.removeClass("fa-warning").addClass("fa-check");
                        },
                        submitHandler: function(form) {
                            var form = $("form#approveFinalForm").serializeJSON();
                            var eventId = $('#eventIdApproveFinal').val();
                            if (eventId == '') {
                            	bootbox.alert("请先选择资产配资");
                            	return;
                            }
                            var js = form.replace('}', ',');
                            var json = js + '"eventId" : "' + eventId + '"}'; 
                            $('#approveFinalConfirm').attr('disabled', true);
                            $.ajax({
                                type: "post",
                                contentType: "application/json; charset=UTF-8",
                                url: ctx + "/assetAllocation/approveFinal",
                                data: json,
                                dataType: "json",
                                success: function(msg) {
                                    if (msg.code == 1) {
                                        bootbox.alert("审批成功！");
                                        modal.modal('hide');
                                        oTable.fnDraw(false);
                    					window.location.reload();
                                    } else {
                                    	modal.modal('hide');
                                        bootbox.alert(msg.message);
                                    }
                                    $('#approveFinalConfirm').attr('disabled', false);
                                },
                                error: function(msg) {
                                    bootbox.alert(msg.message);
                                    modal.modal('hide');
                                    $('#approveFinalConfirm').attr('disabled', false);
                                }
                            });
                        }
                    });

                    $('#approveFinalConfirm').unbind("click").click(function() {
                        timeout(this, 1);
                        approveFinalForm.submit();
                        $("#approveFinalForm")[0].reset();
                    });
                });
                
                //详情
                $('#assetAllocationEditable').on("click", "a.detail", function(e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    window.location.href = ctx + '/assetAllocation/assetDetail/' + id;
                });
                
                //确认打款到账
                $('#assetAllocationEditable').on("click", "a.check", function(e) {
                    e.preventDefault();
                    var obj = $(this);
                    bootbox.confirm("确认银行已打款到账?", function(result) {
                        if (result) {
                            var nRow = obj.parents('tr')[0];
                            var id = nRow.children[0].id;
                            $.ajax({
                                "contentType": "application/json; charset=UTF-8",
                                type: "post",
                                url: ctx + "/assetAllocation/update",
                                data: '{"id":"' + id + '","state":5}',
                                dataType: "json",
                                success: function(msg) {
                                    if (msg.code == 1) {
                                        bootbox.alert("确认成功！");
                                        oTable.fnDraw(false);
                    					window.location.reload();
                                    } else {
                                        bootbox.alert(msg.message);
                                    }
                                },
                                error: function(msg) {
                                    bootbox.alert(msg.message);
                                }
                            });
                        }
                    });
                });
                
                //查询
                $('#queryBtn').click(function() {
                    oTable.fnClearTable();
                });
            }

        };

    }();

    return {
        init: function() {
            editable.init();
        }
    };
}();